import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:partial_refresh/until.dart';

import 'car_model.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      builder: (BuildContext context, Widget? child) {
        return MaterialApp(
          home: MyHomePage(title: '局部刷新小组件'),
          darkTheme: ThemeData.dark(), // 暗色主题
          theme: ThemeData(
            primarySwatch: Colors.blue,
            colorScheme: ColorScheme.fromSeed(seedColor: Color(0xFF2E5BFF)),
          ),
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _title = '点我改变文字';
  final ValueNotifier<String> _valueNotifier = ValueNotifier<String>('点我改变文字');
  final CarService _carService = CarService();
  late final Stream<CarModel?> _carStream;
  late Future<CarModel?> _futureCar;

  @override
  void initState() {
    super.initState();
    _carStream = _carService.getCarStream();
    _futureCar = _carService.fetchCar();
  }

  Widget _statefulBuilderWidget() {
    return StatefulBuilder(
      builder: (context, buildSetState) {
        return InkWell(
          onTap: () {
            _title = _carService.getTitle();
            buildSetState.call(() {});
          },
          child: Container(
            width: double.infinity,
            color: Colors.white,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 18.w),
            child: Text(_title),
          ),
        );
      },
    );
  }

  Widget _valueNotifierWidget() {
    return ValueListenableBuilder<String>(
      valueListenable: _valueNotifier,
      builder: (context, value, child) {
        return InkWell(
          onTap: () {
            _valueNotifier.value = _carService.getTitle();
          },
          child: Container(
            width: double.infinity,
            color: Colors.white,
            alignment: Alignment.center,
            margin: EdgeInsets.symmetric(vertical: 12.h),
            padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 18.w),
            child: Text(value),
          ),
        );
      },
    );
  }

  Widget _streamBuilderWidget() {
    return StreamBuilder<CarModel?>(
      stream: _carStream,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, color: Colors.red, size: 60),
              const SizedBox(height: 16),
              Text(
                '出错啦: ${snapshot.error}',
                style: Theme.of(context).textTheme.bodyLarge,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              FilledButton(
                onPressed: _refreshData, // 出错后可以重试
                child: const Text('重试'),
              ),
            ],
          );
        } else if (snapshot.hasData) {
          return Container(
            color: Colors.blue,
            padding: const EdgeInsets.all(8.0),
            child: Text(snapshot.data?.description ?? ""),
          );
        } else {
          return const CircularProgressIndicator();
        }
      },
    );
  }

  Widget _futureBuilderWidget() {
    return FutureBuilder<CarModel?>(
      future: _futureCar,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, color: Colors.red, size: 60),
              const SizedBox(height: 16),
              Text(
                '出错啦: ${snapshot.error}',
                style: Theme.of(context).textTheme.bodyLarge,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              FilledButton(
                onPressed: _refreshStream, // 出错后可以重试
                child: const Text('重试'),
              ),
            ],
          );
        }
        if (snapshot.hasData) {
          final CarModel? carModel = snapshot.data;
          return Container(
            color: Colors.red,
            padding: const EdgeInsets.all(8.0),
            child: Text(carModel?.description ?? ''),
          );
        }
        return const CircularProgressIndicator();
      },
    );
  }

  void _refreshData() {
    setState(() {
      _futureCar = _carService.fetchCar();
    });
  }

  void _refreshStream() {
    setState(() {
      _carStream = _carService.getCarStream();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          _statefulBuilderWidget(),
          _valueNotifierWidget(),
          _streamBuilderWidget(),
          _futureBuilderWidget(),
        ],
      ),
    );
  }
}
